package com.hz.web.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

import com.alibaba.fastjson.JSONObject;

public class HttpUtils {
	
	/**
	 * 连接超时时间(单位毫秒)
	 */
	private static int CONNECTIONTIMEOUT = 120000;
	/**
	 * 读数据超时时间(单位毫秒)
	 */
	private static int SOTIMEOUT = 120000;
	
	
	public static String httpClient(JSONObject json, String url) throws Exception {
		// 实例化httpClient
		HttpClient httpClient = new HttpClient(new HttpClientParams(),new SimpleHttpConnectionManager(true));
		// 设置编码格式
		httpClient.getParams().setContentCharset("UTF-8");
		// 设置超时时间
		HttpConnectionManagerParams managerParams = httpClient
				.getHttpConnectionManager().getParams();
		// 设置连接超时时间(单位毫秒)
		managerParams.setConnectionTimeout(CONNECTIONTIMEOUT);
		// 设置读数据超时时间(单位毫秒)
		managerParams.setSoTimeout(SOTIMEOUT);
		/*Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
		  Protocol.registerProtocol("https", myhttps);*/
		
		// 构造PostMethod的实例
		PostMethod postMethod = new PostMethod(url);
		Map<String, String> map = new HashMap<String, String>();
		/*map.put("", json.toString());*/
		
		RequestEntity entity = new StringRequestEntity(json.toString(),
				"application/json", "UTF-8");//body层
		
		postMethod.setRequestEntity(entity);
		postMethod.addRequestHeader("Content-Type","application/json;charset=UTF-8");
		postMethod.addRequestHeader("requestHeaders",JSONObject.toJSONString(map));//头部
		// 执行postMethod
		int statusCode = -1;
		JSONObject retJson = new JSONObject(); 
		try {
			statusCode =httpClient.executeMethod(postMethod);
			if (statusCode == HttpStatus.SC_OK) {
				return postMethod.getResponseBodyAsString();
			} else {
				retJson.put("resultCode", statusCode);
				retJson.put("resultInfo", "");
				retJson.put("resultMsg", "请求失败!");
				return retJson.toJSONString();
			}
		} catch (Exception e) {
			retJson.put("resultCode", "300");
			retJson.put("resultInfo", e.getMessage());
			retJson.put("resultMsg", "请求异常!");
			return retJson.toJSONString();
		}
	}

}
